package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.util.DateTimeZoneConverter;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-28
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper,Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询产品
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {

        //校验参数
        if(StringUtils.isEmpty(productKey)){
            throw new BaseException("产品key不能为空");
        }


        //查询产品
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response;
        try {
            response = client.showProduct(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }

        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if(CollUtil.isEmpty(serviceCapabilities)){
            return AjaxResult.success(Collections.emptyList());
        }

        return AjaxResult.success(serviceCapabilities);
    }

    /**
     * 查询设备服务属性
     *
     * @param iotId
     * @return
     */
    @Override
    public AjaxResult queryServiceProperties(String iotId) {

        //调用设备影子接口
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response;
        try {
            response = client.showDeviceShadow(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备服务属性，调用失败");
        }

        //拼装数据
        List<DeviceShadowData> shadow = response.getShadow();
        if(ObjectUtil.isEmpty(shadow)){
            return AjaxResult.success(Collections.emptyList());
        }
        DeviceShadowProperties reported = shadow.get(0).getReported();
        //转换为jsonObject,本质是一个map,方便取数据
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());

        //处理上报时间
        String eventTimeStr = reported.getEventTime();
        LocalDateTime localDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(localDateTime);

        List<Map<String,Object>> list = new ArrayList<>();

        //遍历map
        jsonObject.forEach((k,v)->{
            Map<String,Object> map = new HashMap<>();
            map.put("functionId",k);
            map.put("eventTime",eventTime);
            map.put("value",v);
            list.add(map);
        });


        return AjaxResult.success(list);
    }

    /**
     * 查询设备详情
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo getInfo(String iotId) {

        //根据iotid查询设备
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if(ObjectUtil.isEmpty(device)){
            return null;
        }

        //根据iotid查询iot平台中的设备数据
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
           e.printStackTrace();
           throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }

        //合并DeviceDetailVo

        //属性拷贝
        DeviceDetailVo detailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        //设备状态
        detailVo.setDeviceStatus(response.getStatus());
        //激活时间
        String activeTime = response.getActiveTime();
        if(StringUtils.isNotEmpty(activeTime)){
            LocalDateTime parse = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
            LocalDateTime localDateTime = DateTimeZoneConverter.utcToShanghai(parse);
            detailVo.setActiveTime(localDateTime);
        }

        return detailVo;
    }

    /**
     * 注册设备
     * @param dto
     */
    @Override
    public void registerDevice(DeviceDto dto) {

        //查询设备名称是否重复
        long count = count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()));
        if(count > 0){
            throw new BaseException("设备名称重复,请重新选择");
        }

        //查询设备标识是否重复
        count = count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId()));
        if(count > 0){
            throw new BaseException("设备标识码重复,请重新选择");
        }

        //判断同一个位置是否绑定相同的产品
        /*count = count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(dto.getPhysicalLocationType() != null,Device::getPhysicalLocationType, dto.getPhysicalLocationType()));*/
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getProductKey, dto.getProductKey());
        queryWrapper.eq(Device::getBindingLocation, dto.getBindingLocation());
        queryWrapper.eq(Device::getLocationType, dto.getLocationType());
        if(dto.getLocationType() == 0){
            queryWrapper.eq(Device::getPhysicalLocationType, -1);
        }else {
            queryWrapper.eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType());
        }
        //调用请求
        count = count(queryWrapper);

        if(count > 0){
            throw new BaseException("该老人/位置已绑定产品，请重新选择");
        }

        //保存设备  IOT平台
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withNodeId(dto.getNodeId());
        body.withProductId(dto.getProductKey());
        body.withDeviceName(dto.getDeviceName());
        //秘钥，需要手动设置
        AuthInfo authInfo = new AuthInfo();
        //生成一个秘钥
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.withSecret(secret);
        body.withAuthInfo(authInfo);
        request.withBody(body);
        AddDeviceResponse response;
        try {
            response = client.addDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }

       /* //判断状态码,安全性校验
        if(response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }*/

        //保存设备信息到数据库
        Device device = BeanUtil.toBean(dto, Device.class);
        //设备id
        device.setIotId(response.getDeviceId());
        //秘钥单独保存
        device.setSecret(secret);

        //如果位置类型为0（随身设备），把物理位置类型改为-1
        if(dto.getLocationType() == 0){
            device.setPhysicalLocationType(-1);
        }

        save(device);
    }

    /**
     * 查询所有产品
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //查询redis
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        if(StringUtils.isEmpty(jsonStr)){
            return Collections.emptyList();
        }
        //把json字符串转换对象
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 同步产品列表  到IOT平台
     */
    @Override
    public void syncProductList() {
        //从iot平台获取产品列表
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = client.listProducts(request);
        /*if(response.getHttpStatusCode() != 200){
            throw new BaseException("同步产品列表失败");
        }*/

        //存储到redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));

    }

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device)?1:0;
    }

    /**
     * 修改设备
     * 
     * @param dto 设备
     * @return 结果
     */
    @Override
    public int updateDevice(DeviceDto dto)
    {
        //修改iot平台的数据
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        //条件，设备id
        request.withDeviceId(dto.getIotId());
        UpdateDevice body = new UpdateDevice();
        //设备名称
        body.withDeviceName(dto.getDeviceName());
        request.withBody(body);
        UpdateDeviceResponse response;
        try {
            response = client.updateDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 修改设备，调用失败");
        }

        //修改本地数据
        Device device = BeanUtil.toBean(dto, Device.class);
        try {
            return updateById(device)?1:0;
        } catch (Exception e) {
            throw new BaseException("相同的位置不能绑定同一个产品");
        }
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除设备信息
     * 
     * @param iotId 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(String iotId)
    {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        try {
            client.deleteDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 删除设备，调用失败");
        }

        return remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId))?1:0;
    }

}
